﻿
using System;
using TestBat.IModels.Domain;


namespace TestBat.Models.Domain
{
    public class DomainEntity : IDomainEntity
    {
        public virtual Guid ID { get; set; }

        public override bool Equals(object obj)
        {
            IDomainEntity other = obj as IDomainEntity;

            if (other == null)
                return false;

            // handle the case of comparing two NEW objects
            bool otherIsTransient = Equals(other.ID, Guid.Empty);
            bool thisIsTransient = Equals(ID, Guid.Empty);

            if (otherIsTransient && thisIsTransient)
                return ReferenceEquals(other, this);

            return other.ID.Equals(ID);
        }

        public override int GetHashCode()
        {
            // Once we have a hash code we'll never change it
            if (oldHashCode.HasValue)
                return oldHashCode.Value;

            bool thisIsTransient = Equals(ID, Guid.Empty);

            // When this instance is transient, we use the base GetHashCode()
            // and remember it, so an instance can NEVER change its hash code.
            if (thisIsTransient)
            {
                oldHashCode = base.GetHashCode();
                return oldHashCode.Value;
            }

            return ID.GetHashCode();

        }

        public static bool operator==(DomainEntity x, DomainEntity y) // HACK: doesn't seem to work
        {
            return Equals(x, y);
        }

        public static bool operator!=(DomainEntity x, DomainEntity y) // HACK: doesn't seem to work
        {
            return !(x == y);
        }

        private int? oldHashCode;
    }
}
